package io_learn.object_io;


import org.junit.Test;

import java.io.*;

public class ObjectIoTest {

    /**
     * 把对象写入文件中
     * 序列化会序列化对象的所有引用对象
     * @throws IOException
     */
    @Test
    public void writeObjectToFile() throws IOException {

        Student student = new Student("张三", "30");
        Student tz=new Student("我是同桌","22");
        Student tz2=new Student("我是同桌2","223");
        tz.setTz(tz2);
        student.setTz(tz);

        FileOutputStream baos = new FileOutputStream(new File("C://123.java"));

        ObjectOutputStream outputStream = new ObjectOutputStream(baos);

        outputStream.writeObject(student);

    }


    /**
     * 从文件中加载对象
     *
     * @throws IOException
     */
    @Test
    public void readObjectFromFile() throws IOException, ClassNotFoundException {

        FileInputStream fin = new FileInputStream(new File("C://123.java"));
        ObjectInputStream ois = new ObjectInputStream(fin);

        Student student = (Student)ois.readObject();

        System.out.println(student.getTz().getTz().getName());
        System.out.println(student.toString());

    }

    /**
     * 从内存中读取一个序列化的对象
     */
    @Test
    public void readObjectFromMemory() throws IOException, ClassNotFoundException {

        Student student = new Student("张三", "30");

        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        ObjectOutputStream outputStream = new ObjectOutputStream(baos);

        outputStream.writeObject(student);

        byte[] bytes =baos.toByteArray();
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Object o = ois.readObject();
        System.out.println(o);


    }






}
